
#include "gmatlab.h"

// void g_signal_connect(GObject *obj, gchar *detailed_signal, mxArray *func, [mxArray *data], [gboolean after]);
void mexFunction(int nlhs, mxArray *lhs[], int nrhs, mxArray *rhs[])
{
  GObject *obj;
  gchar *signal;
  mxArray *func, *data = NULL;
  gboolean after = FALSE;

  // Check and convert arguments
  if (nrhs < 3 || nrhs > 5) g_matlab_error("gmatlab:numArg", "g_signal_connect() takes 3-5 arguments");
  if (nlhs != 0) g_matlab_error("gmatlab:numRet", "g_signal_connect() has 0 return values");
  if (mxGetNumberOfElements(rhs[0]) != 1) g_matlab_error("gmatlab:badArray", "g_signal_connect: Arg 1 must have one element");
  if (mxGetClassID(rhs[0]) != MX_GPOINTER)
    g_matlab_error("gmatlab:badArray", "g_signal_connect: Arg 1 must be int, not %s", mxGetClassName(rhs[0]));
  obj = ((gpointer*)mxGetData(rhs[0]))[0];
  g_object_matlab_ensure(obj, rhs[0]);
  g_matlab_cleanup_add(g_object_unref, obj);
  if (mxGetClassID(rhs[1]) != mxCHAR_CLASS) g_matlab_error("gmatlab:badType", "g_signal_connect: Arg 2 must be char, not %s", mxGetClassName(rhs[1]));
  signal = g_matlab_mxArray_get_utf8(rhs[1]);
  g_matlab_cleanup_add(g_free, signal);
  if (mxGetClassID(rhs[2]) != mxFUNCTION_CLASS) g_matlab_error("gmatlab:badType", "g_signal_connect: Arg 3 must be a function handle, not %s", mxGetClassName(rhs[2]));
  func = rhs[2];
  if (nrhs > 3) data = rhs[3];
  if (nrhs > 4)
  {
    GArgument tmp;
    if (mxGetNumberOfElements(rhs[4]) != 1) g_matlab_error("gmatlab:badArray", "g_signal_connect: Arg 5 must have one element");
    switch (mxGetClassID(rhs[4]))
    {
      case mxLOGICAL_CLASS:
      case mxINT8_CLASS:
      case mxUINT8_CLASS:
      case mxINT16_CLASS:
      case mxUINT16_CLASS:
      case mxINT32_CLASS:
      case mxUINT32_CLASS:
      case mxINT64_CLASS:
      case mxUINT64_CLASS:
      case mxSINGLE_CLASS:
      case mxDOUBLE_CLASS:
        arg_set_from_mxArray(&tmp, GI_TYPE_TAG_BOOLEAN, rhs[4], mxGetClassID(rhs[4]), 0);
        after = tmp.v_boolean;
        break;
      default:
        g_matlab_error("gmatlab:badType", "g_signal_connect: Arg 5 must be numeric/logical, not %s", mxGetClassName(rhs[4]));
        break;
    }
  }
  
  // Call function
  g_signal_matlab_connect(obj, signal, func, data, after);
  
  // Prepare return value

  g_matlab_cleanup();
}
